<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            v-model="queryParams.categoryId"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择商品分类"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable>
            <el-option label="上架" value="on" />
            <el-option label="下架" value="off" />
            <el-option label="审核中" value="pending" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增商品
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
          <el-button type="warning" :disabled="!selectedIds.length" @click="handleBatchOff">
            <el-icon><Bottom /></el-icon>批量下架
          </el-button>
          <el-button type="success" :disabled="!selectedIds.length" @click="handleBatchOn">
            <el-icon><Top /></el-icon>批量上架
          </el-button>
        </div>
      </template>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="productList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品图片" align="center" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.mainImage"
              :preview-src-list="[row.mainImage]"
              fit="cover"
              class="product-image"
            />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name" min-width="200" show-overflow-tooltip />
        <el-table-column label="商品分类" prop="categoryName" min-width="120" />
        <el-table-column label="价格" align="center" width="120">
          <template #default="{ row }">
            <span>¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存" prop="stock" align="center" width="100" />
        <el-table-column label="销量" prop="sales" align="center" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="primary" @click="handleStock(row)">
              <el-icon><Box /></el-icon>库存
            </el-button>
            <el-button
              link
              :type="row.status === 'on' ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              <el-icon>
                <component :is="row.status === 'on' ? 'Bottom' : 'Top'" />
              </el-icon>
              {{ row.status === 'on' ? '下架' : '上架' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="商品分类" prop="categoryId">
              <el-cascader
                v-model="productForm.categoryId"
                :options="categoryOptions"
                :props="{ checkStrictly: true, value: 'id', label: 'name' }"
                placeholder="请选择商品分类"
              />
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="productForm.price"
                :precision="2"
                :step="0.1"
                :min="0"
                placeholder="请输入商品价格"
              />
            </el-form-item>
            <el-form-item label="商品库存" prop="stock">
              <el-input-number
                v-model="productForm.stock"
                :min="0"
                :precision="0"
                placeholder="请输入商品库存"
              />
            </el-form-item>
            <el-form-item label="商品主图" prop="mainImage">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleMainImageSuccess"
                :before-upload="beforeImageUpload"
              >
                <img v-if="productForm.mainImage" :src="productForm.mainImage" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品图片" prop="images">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                list-type="picture-card"
                :file-list="imageList"
                :on-success="handleImageSuccess"
                :on-remove="handleImageRemove"
                :before-upload="beforeImageUpload"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="detail">
            <el-form-item label="商品描述" prop="description">
              <el-input
                v-model="productForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入商品描述"
              />
            </el-form-item>
            <el-form-item label="商品详情" prop="content">
              <el-input
                v-model="productForm.content"
                type="textarea"
                :rows="6"
                placeholder="请输入商品详情"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品规格" name="spec">
            <el-form-item label="规格类型" prop="specType">
              <el-radio-group v-model="productForm.specType">
                <el-radio label="single">单规格</el-radio>
                <el-radio label="multiple">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="productForm.specType === 'multiple'">
              <el-form-item label="规格项">
                <div v-for="(spec, index) in productForm.specs" :key="index" class="spec-item">
                  <el-input v-model="spec.name" placeholder="规格名称" class="spec-name" />
                  <el-tag
                    v-for="(value, valueIndex) in spec.values"
                    :key="valueIndex"
                    closable
                    @close="handleRemoveSpecValue(index, valueIndex)"
                  >
                    {{ value }}
                  </el-tag>
                  <el-input
                    v-if="spec.inputVisible"
                    ref="specInputRef"
                    v-model="spec.inputValue"
                    class="spec-input"
                    size="small"
                    @keyup.enter="handleSpecInputConfirm(index)"
                    @blur="handleSpecInputConfirm(index)"
                  />
                  <el-button v-else class="button-new-tag" size="small" @click="showSpecInput(index)">
                    + 添加规格值
                  </el-button>
                </div>
                <el-button type="primary" link @click="handleAddSpec">
                  <el-icon><Plus /></el-icon>添加规格项
                </el-button>
              </el-form-item>
              <el-form-item label="规格组合">
                <el-table :data="productForm.specCombinations" border>
                  <el-table-column label="规格" min-width="200">
                    <template #default="{ row }">
                      <span v-for="(spec, index) in row.specs" :key="index">
                        {{ spec.name }}: {{ spec.value }}
                        <el-divider v-if="index < row.specs.length - 1" direction="vertical" />
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="价格" width="150">
                    <template #default="{ row }">
                      <el-input-number
                        v-model="row.price"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" width="150">
                    <template #default="{ row }">
                      <el-input-number
                        v-model="row.stock"
                        :min="0"
                        :precision="0"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="编码" width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.code" size="small" />
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getProductList, deleteProduct, updateProductStatus } from '@/api/merchant'
import { getCategoryList } from '@/api/category'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  categoryId: null,
  status: ''
})

// 数据列表
const productList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 分类选项
const categoryOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const activeTab = ref('basic')
const productFormRef = ref()
const productForm = reactive({
  id: undefined,
  name: '',
  categoryId: null,
  price: 0,
  stock: 0,
  mainImage: '',
  images: [],
  description: '',
  content: '',
  specType: 'single',
  specs: [],
  specCombinations: []
})

// 表单校验规则
const productRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  mainImage: [{ required: true, message: '请上传商品主图', trigger: 'change' }]
}

// 图片上传相关
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}
const imageList = ref([])

// 获取商品列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getProductList(queryParams)
    productList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const { data } = await getCategoryList()
    categoryOptions.value = data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.categoryId = null
  queryParams.status = ''
  handleQuery()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增商品
const handleAdd = () => {
  dialogTitle.value = '新增商品'
  dialogVisible.value = true
  resetForm()
}

// 编辑商品
const handleEdit = (row) => {
  dialogTitle.value = '编辑商品'
  dialogVisible.value = true
  Object.assign(productForm, row)
  imageList.value = row.images.map(url => ({ url }))
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该商品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProduct(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  ElMessageBox.confirm(`确认要删除选中的 ${selectedIds.value.length} 个商品吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => deleteProduct(id)))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除商品失败:', error)
    }
  })
}

// 切换商品状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 'on' ? 'off' : 'on'
  try {
    await updateProductStatus(row.id, newStatus)
    ElMessage.success(`${newStatus === 'on' ? '上架' : '下架'}成功`)
    getList()
  } catch (error) {
    console.error('更新商品状态失败:', error)
  }
}

// 批量上架
const handleBatchOn = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要上架的商品')
    return
  }
  ElMessageBox.confirm(`确认要上架选中的 ${selectedIds.value.length} 个商品吗？`, '提示').then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => updateProductStatus(id, 'on')))
      ElMessage.success('批量上架成功')
      getList()
    } catch (error) {
      console.error('批量上架商品失败:', error)
    }
  })
}

// 批量下架
const handleBatchOff = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要下架的商品')
    return
  }
  ElMessageBox.confirm(`确认要下架选中的 ${selectedIds.value.length} 个商品吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => updateProductStatus(id, 'off')))
      ElMessage.success('批量下架成功')
      getList()
    } catch (error) {
      console.error('批量下架商品失败:', error)
    }
  })
}

// 跳转到库存管理
const handleStock = (row) => {
  router.push(`/merchant/product/stock?id=${row.id}`)
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 表单相关
const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
  Object.assign(productForm, {
    id: undefined,
    name: '',
    categoryId: null,
    price: 0,
    stock: 0,
    mainImage: '',
    images: [],
    description: '',
    content: '',
    specType: 'single',
    specs: [],
    specCombinations: []
  })
  imageList.value = []
}

// 提交表单
const submitForm = async () => {
  if (!productFormRef.value) return
  await productFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // TODO: 调用保存商品接口
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('保存商品失败:', error)
      }
    }
  })
}

// 图片上传相关方法
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleMainImageSuccess = (res) => {
  productForm.mainImage = res.data.url
}

const handleImageSuccess = (res) => {
  productForm.images.push(res.data.url)
}

const handleImageRemove = (file) => {
  const index = productForm.images.indexOf(file.url)
  if (index !== -1) {
    productForm.images.splice(index, 1)
  }
}

// 规格相关方法
const handleAddSpec = () => {
  productForm.specs.push({
    name: '',
    values: [],
    inputVisible: false,
    inputValue: ''
  })
}

const handleRemoveSpec = (index) => {
  productForm.specs.splice(index, 1)
  generateSpecCombinations()
}

const showSpecInput = (index) => {
  productForm.specs[index].inputVisible = true
  nextTick(() => {
    specInputRef.value.focus()
  })
}

const handleSpecInputConfirm = (index) => {
  const spec = productForm.specs[index]
  if (spec.inputValue) {
    spec.values.push(spec.inputValue)
  }
  spec.inputVisible = false
  spec.inputValue = ''
  generateSpecCombinations()
}

const handleRemoveSpecValue = (index, valueIndex) => {
  productForm.specs[index].values.splice(valueIndex, 1)
  generateSpecCombinations()
}

const generateSpecCombinations = () => {
  // TODO: 根据规格项生成规格组合
}

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    on: 'success',
    off: 'info',
    pending: 'warning',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    on: '上架',
    off: '下架',
    pending: '审核中',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getList()
  getCategories()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-wrapper {
    margin-bottom: 20px;
  }

  .table-wrapper {
    .card-header {
      display: flex;
      gap: 10px;
    }

    .product-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.spec-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;

  .spec-name {
    width: 120px;
  }

  .spec-input {
    width: 120px;
  }

  .button-new-tag {
    margin-left: 10px;
  }
}

:deep(.el-tag) {
  margin-right: 10px;
  margin-bottom: 5px;
}
</style> 